app.push(function(){
    var Category = function(){
    	var categoryContainer = false;
        var this_ = this;
        var getDataMode = 'get';
        var product = 'product';
        var article = 'article';
        var category = false;
        var type = 'product';
        this.init = function(url){
	        url = app.cloneArray(url || app.currentUrl);
            if(url[1] == 'add' || url[1] == 'add_for_article' || url[1] == 'add_for_product'){
                if(url[1] == 'add_for_articles' || url[1] == 'add_for_products'){
                    type = url[1].split('_')[2];
                }
                url[1] = 'edit';
                currentShop = url[2] + '';
                url[2] = false;
            }
            if(this[url[1]])this[url[1]](url);
            else this.loadCategory((isNaN(app.currentUrl[1]) ? app.currentUrl[2] : app.currentUrl[1])|| 0);
        }
        var showData = function(model,currentShop){
            var categoryContainer = false;
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            if(!currentShop){
                app.go('#shop/list');
                return;
            }
            app.topMenu.breadcrumbList[1] = ['Список категорий ' + (model == "product" ? "товаров" : "статей"),'#category/list/'+currentShop];
            app.topMenu.breadcrumbList[2] = false;
            app.topMenu.buildBreadcrumb();
            app.leftMenu.setEditShopLeftMenu(currentShop);
            var el = $.tmpl('manage_category_list', 
            {
                show_select: app.user_info.user_category > 1,
                shop: currentShop,
                type: model
            });
            categoryContainer = $(el).find('[rel=category_list]:first');
            el.prependTo(app.elements.general_content.html(''));
            mlhAPI.category.getTree({
                shop_name: currentShop,
                model: model,
                requestType: getDataMode,
                callback: function(data){
                    console.log(data);
                    app.main.unmask();
                    if(data.result=='error' || data.data['log']){
                        return;
                    }
                    categoryContainer.html('').prepend($.tmpl('list_sub_category_elements', {
                        list: data.data,
                        type: model
                    }));
                    app.decorate.setEvents(app.elements.general_content);
                }
            });
            getDataMode = 'get';
        }
        this.products = function(url){
            showData(product, url[2]);
        }
        this.articles = function(url){
            showData(article, url[2]);   
        }
        this.list = function(url){
            showData(product, url[2]);   
        }
	    this.loadCategory = function(id){
	        //загружаем шаблон
	        var model = id ? '' : (isNaN(app.currentUrl[1]) ? app.currentUrl[1] : 'shop');
	        mlhAPI.category.get({
	        	id: id,
	        	model: model,
	        	callback: function(info){
	        		console.log(info);
	        		model = model || info.data.element.model;
		        	info.data.element['model_title'] = app.texts[model] ? app.texts[model][1] : model;
					var el = $.tmpl('category', info.data.element);
					categoryContainer = $(el).find('#categoryList');
					el.prependTo(app.elements.general_content.html(''));
                    app.leftMenu.hide();
                    app.main.unmask();
                    app.topMenu.eraseBreadcrumbList();
                    if(info.data.element['category_id']){
                        mlhAPI.category.getTree({
                            id: info.data.element['category_id'],
                            maxLevel:1,
                            callback: function(data){
                                console.log(data);
                                if(data.result=='error' || data.data['log']){
                                    return;
                                }
                                categoryContainer.prepend($.tmpl('sub_category_elements', {list: data.data}));
                            }
                        });
                        if(mlhAPI[info.data.element.model]){
                            mlhAPI[info.data.element.model].get({
                                category_id: info.data.element['category_id'],
                                callback: function(data){
                                    console.log(data);
                                    if(data.result=='error'){
                                        return;
                                    }
                                    var content = "Нет записей";
                                    if(data.data.element.length) content = $.tmpl(info.data.element.model, data.data.element);
                                    categoryContainer.append(content);
                                }
                            });
                        }
                        this_.buildcategoryBreadcrumb(info.data.element['category_id'],true);
                     }
	        	}
	        });
        }
        this.buildcategoryBreadcrumb = function(category_id, noLast){
        	if(!category_id) return;
        	mlhAPI.category.road({
	            id: category_id,
	            callback: function(data){
		            console.log(data);
		            if(data.result!='error' && data.data['list']){
			            var start = app.topMenu.breadcrumbList.length;
			            for(var k in data.data.list){
			            	if(category_id == data.data.list[k].category_id && noLast) break;
			            	app.topMenu.breadcrumbList[start++] = [data.data.list[k].title,'#category/'+data.data.list[k].category_id,'category'];
			            }
		            }
		            app.topMenu.buildBreadcrumb();

	        	}
			});
        }
        this.edit = function(url){
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            category = url[2] ? url[2] : false;
            if(!category){
                this.build({
                    model: type
                });
                app.main.unmask();
                app.leftMenu.setEditShopLeftMenu(currentShop);
            }else{
                mlhAPI.get({
                    c: 'category',
                    v: 'display',
                    id: category,
                    requestType: 'get_nc'
                },function(data){
                    console.log("category data", data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    currentShop = data.data.element['shop'];
                    type = data.data.element['model'];
                    this_.build(data.data.element);
                    app.topMenu.breadcrumbList[1] = ['Список категорий ' + (type == product ? "товаров" : "статей"),'#category/list/' + currentShop];
                    app.topMenu.breadcrumbList[2] = [data.data.element['title'],'#category/edit/' + category];
                    app.topMenu.buildBreadcrumb();
                    app.leftMenu.setEditShopLeftMenu(currentShop);
                });
            }
            if(category){
                $('#categoryEditForm button[type=submit]').text('Редактировать магазин');
            }
            
        }
        this.build = function(data){
            jQuery.extend(data, {
                editMode: category!=false
            });
            var el = $.tmpl('edit_category',data);
            el.prependTo(app.elements.general_content.html(''));
            app.decorate.validateRule($('#categoryEditForm input, #categoryEditForm textarea'),
            {
                success: ' ',
                endValid: function(error){
                    if(!error){
                        $('#categoryEditForm .control-group').each(function(){
                            if($(this).hasClass('error')) error = true;
                            $(this).find('*[rel=req]').each(function(){
                                var value = $(this).val();
                                if(!value) error = true;
                            });
                        });
                    }
                    $('#categoryEditForm button[type=submit]').attr('class', !error ? 'btn btn-success' : 'btn btn-warning');
                    if(!error){
                       $('#categoryEditForm').find('.alert-info').show();
                       $('#categoryEditForm').find('.alert[data-type=error]').hide();
                    }
                }
            });

            $('#categoryEditForm form').submit(function(){
                if($('#categoryEditForm button[type=submit]').hasClass('btn-warning')){
                    $('#categoryEditForm').find('.alert[data-type=error]').addClass('alert-error').text("Заполните все необходимые поля").show();
                    $('#categoryEditForm').find('.alert-info').hide();
                    $('#categoryEditForm').find('*[rel=req]').each(function(){
                        var value = $(this).val();
                        if(!value) {
                            $(this).parents('.control-group:first')
                                .attr('class','row control-group warning span12 no_left_margin')
                                .find('.alert:first').text('Это поле обязательно надо заполнить').show();
                            
                        }
                    });
                    return false;
                }
                var formData = {
                    callback: function(data){
                        console.log(data);
                        if(data.data['errors'] || data.data['error']){
                            var text = "";
                            if(data.data['errors']){
                                for(var k in data.data.errors){
                                    if(k=='email')$('#categoryEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                                    text += "<div>" + data.data.errors[k] +"</div>";
                                }
                            }else{
                                text += "<div>" + data.data['error'] +"</div>";
                            }
                            $('#categoryEditForm').find('.alert[data-type=error]').addClass('alert-error').html(text).show();
                            $('#categoryEditForm').find('.alert-info').hide();
                            $('#categoryEditForm button[type=submit]').attr('class', 'btn btn-warning');
                        }else{
                            $('#categoryEditForm').find('.alert[data-type=error]').hide();
                            $('#categoryEditForm button[type=submit]').attr('class', 'btn btn-success');
                            app.static.success({description:(category ? 'Вы успешно отредактировали категорию' : 'Вы успешно создали категорию')})
                            getDataMode = 'get_rc';
                            app.go('#category/list/' + currentShop);
                        }
                    }
                }
                if(category) formData['category_id'] = category;
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                formData['shop'] = currentShop;
                if(type == product){
                    var params = $('#categoryParams [rel=param_element]');
                    if(params.length){
                        var tmp=0;
                        params.each(function(){
                            formData['paramId_'+tmp] = $(this).find('input[rel=paramId]:first').val();
                            formData['paramType_'+tmp] = $(this).find('input[rel=paramType]:first').val();
                            formData['paramName_'+tmp] = $(this).find('input[rel=paramName]:first').val();
                            formData['paramValue_'+tmp] = $(this).find('input[rel=paramValue]:first').val();
                            formData['paramDescription_'+tmp] = $(this).find('input[rel=paramDescription]:first').val();
                            tmp++;
                        });
                    }
                }
                console.log(formData);
                mlhAPI.category.set(formData);
                return false;
            });
            if(type == product){
                var typeNameList = ['Число','Cтрока','Текст','Дата','Вы выбираете из:','Пользователь выбирает из','Флаг ДА/НЕТ','',''];
                var paramContainer = $('#categoryParams').html('');
                var newContainer = $('#newCategoryParam');
                var setElementEvents = function(el){
                    el.find('[rel=remove]:first').click(function(){
                        var parent = $(this).parents('[rel=param_element]');
                        if(parent.find('input[rel=paramId]').val()){
                            app.static.prompt({
                                title: "Удаление параметра",
                                description: "Все данные этого параметра удалятся у всех таваров с этой категории! Вы действительно хотите удалить этот параметр?",
                                buttons:[
                                    {
                                        name: "Отмена",
                                        action: function(){
                                            $('#helpWindow').modal('hide');
                                        }
                                    },
                                    {
                                        name: "Удалить",
                                        className: "btn-danger",
                                        action: function(){
                                            parent.remove();
                                            $('#helpWindow').modal('hide');
                                        }
                                    }
                                ]
                            })
                        }else{
                           parent.remove();
                        }
                    });
                    el.find('[rel=up]:first').click(function(){
                        var el = $(this).parents('[rel=param_element]');
                        if(!el.prev().length) return;
                        var prev = el.prev();
                        el = el.remove();
                        prev.before(el);
                        setElementEvents(el);
                    });
                    el.find('[rel=down]:first').click(function(){
                        var el = $(this).parents('[rel=param_element]');
                        if(!el.next().length) return;
                        var next = el.next();
                        el = el.remove();
                        next.after(el);
                        setElementEvents(el);
                    });
                }
                var setElementItem = function(data){
                    var el = $.tmpl('edit_category_param_element',data);
                    el.appendTo(paramContainer);
                    setElementEvents(el);
                }
                if(category>0){
                    mlhAPI.param.getList({
                        category_id: category,
                        callback: function(data){
                            console.log(data);
                            if(data.result=='error'){
                                return;
                            }
                            var paramData = [];
                            if(data.data.list.length){
                                $(data.data.list).each(function(){
                                    paramData.push({
                                        type:this.type,
                                        typeName: typeNameList[this.type],
                                        name: this.title,
                                        description: this.description,
                                        value: this.values,
                                        param_id: this.param_id
                                    });
                                });
                                setElementItem(paramData);
                            }
                        }
                    });
                }
                paramContainer.parent().parent().show();
                var newName = newContainer.find('[rel=newName]:first').click(function(){
                    $(this).parent().removeClass('error');
                });
                var newDescription = newContainer.find('[rel=newDescription]:first');
                var newValue = newContainer.find('[rel=newValue]:first').click(function(){
                    $(this).parent().removeClass('error');
                });
                newContainer.find('[rel=newType]:first').change(function(){
                    newName.parent().show().removeClass('error');
                    newDescription.parent().show();
                    newValue.parent().hide();
                    switch($(this).val()*1){
                        case 8:{
                            newValue.parent().hide();
                            newName.parent().hide();
                            newDescription.parent().hide();
                        }
                        break ;
                        case 7:{
                            newValue.parent().hide();
                            newDescription.parent().hide();
                        }
                        break ;
                        case 4:
                        case 5:{
                            newValue.parent().show().removeClass('error');
                        }
                        break;
                    }
                });

                newContainer.find('[rel=addNew]:first').click(function(){
                    var valid = false;
                    var type = newContainer.find('[rel=newType]:first').val()*1;
                    var data = {
                        type:type,
                        typeName: typeNameList[type],
                        name: newName.val(),
                        description: newDescription.val(),
                        value: newValue.val().split(',').join(', ')
                    };
                    switch(type){
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 6:{
                            if(newName.val()) valid = true;
                            else newName.parent().addClass('error');
                        }

                        break ;
                        case 4:
                        case 5:{
                            if(newName.val()) valid = true;
                            else newName.parent().addClass('error');

                            if(newValue.val()) valid = true;
                            else newValue.parent().addClass('error');
                        }
                        break;
                        case 7:{
                            if(newName.val()) valid = true;
                            else newName.parent().addClass('error');
                            data.description = false;
                            data.value = false;
                        }
                        case 8:{
                            valid = true;
                        }
                        break ;
                    }
                    if(!valid) return;
                    setElementItem(data);
                    newValue.val('');
                    newName.val('');
                    newDescription.val('');
                });
            }
        }
    }
    
    app['category'] = new Category();
})


